from komponents.ajax.widgets import *
from django import forms
from django.forms.widgets import TextInput
from django.core.urlresolvers import reverse, resolve, NoReverseMatch
from komponents import settings

class DateField(forms.DateField):
    widget = CalendarWidget()

    def __init__(self, input_formats=None, *args, **kwargs):
        super(DateField, self).__init__(*args, **kwargs)
        self.input_formats = input_formats or settings.DEFAULT_DATE_INPUT_FORMATS

class TimeField(forms.TimeField):
    widget = TimeEntryWidget()


        
#class NameField(forms.CharField):
#    
#    def pre_save(self, model_instance, add):
#        "Returns field's value just before saving."
#        return getattr(model_instance, self.attname)
#    
#    def to_python(self, value):
#        if isinstance(value, basestring):
#            return value
#        if value is None:
#            if self.null:
#                return value
#            else:
#                raise exceptions.ValidationError(
#                    ugettext_lazy("This field cannot be null."))
#        return smart_unicode(value)
    

class AjaxModelChoiceField( forms.ModelChoiceField ):
        
    def __init__(self, ajax_service, extra_filter=None, empty_label='', widget_attrs={}, *args, **kwargs):
        self.ajax_service = ajax_service        
        opt = {
#               'mustMatch': 'true', 
#               'autoFill': 'true',
               'minChars': '0',
#               'matchContains': 'true',
#               'selectFirst': 'false',
                }  
        widget_attrs['autocomplete_options'] = kwargs.pop('autocomplete_options',{})
        self.choices = []
                  
        super(AjaxModelChoiceField, self).__init__(None,
                                              widget=AjaxLookupInput( ajax_service, attrs=widget_attrs),
                                              empty_label = empty_label,
                                              *args, **kwargs)
        
    def add_filter(self, **kwargs):
        for k,v in kwargs.items():
            self.widget.add_filter(k, v) 
        
    def _get_queryset(self):
        if not self._queryset:
            try:
                service, args, kwargs= resolve( reverse(self.ajax_service) )
                self._queryset = service.queryset
            except NoReverseMatch, e:
                raise NoReverseMatch( "Error reversing %s " % self.ajax_service )
            
        return self._queryset

    def _set_queryset(self, queryset):
        if queryset and hasattr(queryset, 'core_filters'):
            self._queryset = queryset        
            for k, v in queryset.core_filters.items():        
                self.widget.add_filter(k, v)
        elif queryset != None:
            raise Exception('Only related queryset are allowed in %s. plese use <add_filter> method or filter AjaxService' % self.__class__.__name__)
        else:
            self._queryset = queryset

        
    queryset = property(_get_queryset, _set_queryset)                  
                
    def clean(self, value):
        if not value: 
            if self.required:
                raise forms.ValidationError(self.error_messages['required'])
            obj = None
        else:
            try: 
                obj = self.queryset.get( pk=value )
            except self.queryset.model.DoesNotExist:
                raise forms.ValidationError(self.error_messages['invalid_choice'])     
             
        return obj   
    


    
    def widget_attrs(self, widget):
        return {'autocomplete': 'off'} 
    
